import { Component, OnInit } from '@angular/core';
import {GovInfo} from "../govinfos";
import {GovinfosService} from "../govinfos.service";
import {ActivatedRoute, Router} from "@angular/router";
import {ResponseUtil} from "../../../../util/response-util";
import {LogUtil} from "../../../../util/log-util";
import {PageSubject} from "../../../../util/page-subject";
import {Path} from "../../../../portal/admin/admin-breadcrumb/breadcrumb";
import {Dialog} from "../../../../widgets/one-dialog/dialog";
import {OneDialogService} from "../../../../widgets/one-dialog/one-dialog.service";
import {MsgResult} from "../../../../models/msg-result";
import {FormBuilder, FormGroup, Validators} from "@angular/forms";
import {MsgConstants} from "../../../../constants/constants";

declare var $;

@Component({
  selector: 'app-govinfo-update',
  templateUrl: './govinfo-update.component.html'
})
export class GovinfoUpdateComponent implements OnInit {

  //声明实体
  govInfo :GovInfo;
  //定义变量id
  id : string;
  govForm : FormGroup;
  treeObj;
  constructor(
    private route :ActivatedRoute,
    private router :Router,
    private responseUtil: ResponseUtil,
    private fb: FormBuilder,
    private pageSubject : PageSubject,
    private dialogService : OneDialogService,
    private govInfosService :GovinfosService
  ) {
   this.initObject();
  }

  ngOnInit() {

    //初始化修改表单
    this.initGovUpdate();

    this.pushPage();

    this.administrativeDivisionTree();
  }

  /**
   * 面包屑导航
   */
  pushPage(){
    let path = new Path("权限系统","");
    this.pageSubject.pushPage("政府管理","修改",path);
  }

  //根据id查询初始化修改页面
  initGovUpdate(){
    let id = this.route.snapshot.params['govId'];
    this.govInfosService.getGovInfoById(id).subscribe(
      result=>this.responseUtil.success(result,this.processGetResult),
      message => this.responseUtil.error(message)
    );
  }
  /**
   * id查询成功后调用
   * @param json
   */
  private processGetResult = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.govInfo = result.data;
      console.log(this.govInfo);
      this.govForm.patchValue(this.govInfo);
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }

  onSubmit(){
    this.govInfosService.updateGovInfo(this.govForm.value).subscribe(
      result=>this.responseUtil.success(result,this.processGovUpdateResult),
      message => this.responseUtil.error(message)
    );
  }
  /**
   *  获取修改信息
   * @param json
   */
  private processGovUpdateResult = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.dialogService.success(result.message, () => this.cancelGovUpdate());
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }

  //取消修改方法
  cancelGovUpdate(){
    this.router.navigate(['..'],{relativeTo : this.route})
  }
  /**
   * 实例化对象
   */
  private initObject(){
    this.govInfo =new GovInfo("","","","","","",'',"","");
    this.buildForm();
  }
  /**
   * 构造表单
   */
  buildForm(): void {
    this.govForm = this.fb.group({
      'id': [this.govInfo.id],
      'name': [this.govInfo.name, [
        Validators.required,
        Validators.maxLength(30)
      ]],
      'regionCode': [this.govInfo.regionCode],
      'regionName': [this.govInfo.regionCode, [
        Validators.required
      ]],
      'phone': [this.govInfo.phone, [
        Validators.maxLength(14),
        // Validators.pattern(/(^(((13[0-9]{1})|(15[0-9]{1}))+\d{8})$)|(^\d{3,4}-?\d{7,9}$)/)
        Validators.pattern(/^(((13[0-9]{1})|(15[0-9]{1})|18[0-9]{1})+\d{8})|((((\d{3,4})-))(\d{7,9}))$/)
      ]],
      'remark': [this.govInfo.remark, [
        Validators.maxLength(30)
      ]],
      'isValid': [this.govInfo.isValid = '0', [
        Validators.required,
        Validators.maxLength(1)
      ]],
      'isDisable': [this.govInfo.isDisable = '1', [
        Validators.required,
        Validators.maxLength(1)
      ]]
    });

    this.govForm.valueChanges.subscribe(
      data => this.onValueChanged(data)
    );
    this.onValueChanged();
  }
  /**
   * 值变化监听
   * @param data
   */
  onValueChanged(data?: any) {
    if (!this.govForm) {
      return;
    }
    const form = this.govForm;
    for (const field in this.formErrors) {
      this.formErrors[field] = '';
      const control = form.get(field);
      if (control && control.dirty && !control.valid) {
        const messages = this.validationMessages[field];
        for (const key in control.errors) {
          this.formErrors[field] += messages[key] + ' ';
        }
      }
    }
  }

  /**
   * 校验字段
   * @type {{name: string; code: string}}
   */
  formErrors = {
    'name': '',
    'regionName': '',
    'phone': ''
  };

  /**
   * 校验提示信息
   * @type {{name: {required: string; maxlength: string}; code: {required: string; maxlength: string; pattern: string}}}
   */
  validationMessages = {
    'name': {
      'required': '政府机构名称不能为空',
      'maxlength': '长度不能超过30',
    },
    'regionName': {
      'maxlength': '行政区划不能为空',
    },
    'phone': {
      'maxlength': '长度不能超过14位',
      'pattern': '格式不正确'
    }
  };


  /**
   * 获取行政区划树
   */
  administrativeDivisionTree() {
    this.govInfosService.getRetrieveRegionsTree().subscribe(
      result => this.responseUtil.success(result, this.processRegionsTreeResult),
      message => this.responseUtil.error(message)
    );
  }
  /**
   * 对行政区划树结果处理
   * @param result
   */
  private processRegionsTreeResult = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      //初始化zTree
      this.regioCodezTree(result.data);
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }

  regioCodezTree(data){

    let setting = {
      callback: {
        onClick: this.clickTree
      }
    };

    let zNodes =data;

    this.treeObj = $.fn.zTree.init($("#gov_update_ZTree"), setting, zNodes);
  }
  clickTree = (event, treeId, treeNode) =>{
    this.govInfo = this.govForm.value;
    this.govInfo.regionCode = treeNode.id;
    this.govInfo.regionName = treeNode.name;
    this.govForm.patchValue(this.govInfo);
  };


}
